﻿using Newtonsoft.Json;
using System;
using System.Net.Http;
using System.Threading.Tasks;

namespace FileUploadApp
{
    public class APIService
    {
        public static string errMsg { get; set; }



        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public static async Task<bool> UploadFile(UploadFileObj request)
        {
            try
            {
                var url = LoginUser.InterfaceUrl + "/Upload/SubmitBase64";
                var client = LoginUser.httpClientFactory.CreateClient();

                var json = JsonConvert.SerializeObject(request);
                StringContent content = new StringContent(json);
                content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");

                var resp = await client.PostAsync(url, content);

                // 检查响应状态码，处理可能的404错误
                if (resp.StatusCode == System.Net.HttpStatusCode.NotFound)
                {
                    errMsg = "上传接口未找到，请检查URL是否正确。";
                    return false;
                }

                resp.EnsureSuccessStatusCode();
                var str = await resp.Content.ReadAsStringAsync();
                var rep = JsonConvert.DeserializeObject<Res<string>>(str);

                if (rep.code == 1)
                {
                    return true;
                }
                else
                {
                    errMsg = rep.msg;
                    return false;
                }
            }
            catch (HttpRequestException httpEx)
            {
                errMsg = $"网络请求异常: {httpEx.Message}";
                return false;
            }
            catch (Exception ex)
            {
                errMsg = $"未知错误: {ex.Message}";
                return false;
            }
        }


    }
}
